package com.qfedu.common.core.interceptor;

import com.qfedu.common.core.annotation.NoLoginCheck;
import com.qfedu.common.core.constant.CommonConstant;
import com.qfedu.common.core.exception.CommonException;
import com.qfedu.common.core.utils.JwtUtils;
import com.qfedu.common.core.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 控制器的方法封装为HandlerMethod对象
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            // 判断方法是否使用了指定的注解
            boolean ret = method.isAnnotationPresent(NoLoginCheck.class);
            if (ret) {
                return true;
            }
            String token = request.getHeader(CommonConstant.TOKEN);
            if (token == null || token.isEmpty()) {
                throw new CommonException("请重新登录");
            }
            /*
            RedisUtil redisUtil = SpringBeanUtils.getBean(RedisUtil.class);
            User user = redisUtil.getCacheObject(String.format(RedisKeyEnum.KEY_LOGIN.getKey(), token));
            if (user == null) {
                throw new CommonException("请重新登录");
            }*/
            try {
                Claims claims = JwtUtils.parseJWT(token);
                Integer uid = (Integer) claims.get("uid");
                // 将用户id写入ThreadLocal
                UserUtils.setUid(uid);
            } catch (Exception e) {
                throw new CommonException("请重新登录");
            }
        }

        return true;
    }

    // 控制层接口执行完后，从ThreadLocal中删除用户id（本质上从当前线程的ThreadLocalMap对象中删除）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtils.removeUid();
    }

    /*@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Token");
        if (token == null || token.isEmpty()) {
            throw new CommonException("请重新登录");
        }
        RedisUtil redisUtil = SpringBeanUtils.getBean(RedisUtil.class);
        User user = redisUtil.getCacheObject("token:" + token);
        if (user == null) {
            throw new CommonException("请重新登录");
        }
        return true;
    }*/
}
